package cn.e4j.modular.crm.controller;

import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.PageReData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.StringUtils;
import cn.e4j.modular.common.service.SysAuthorityService;
import cn.e4j.modular.crm.entity.GwecT;
import cn.e4j.modular.crm.service.impl.GwecTServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static java.math.BigDecimal.ROUND_HALF_DOWN;

/**
 * 发货通知单管理
 * Created by miaoyl on 2019-03-07.
 */
@Controller
@RequestMapping("/crm/gwai750")
public class Gwai750Controller extends BaseController {

    @Autowired
    private GwecTServiceImpl gwecTService;

    @Autowired
    public SysAuthorityService sysAuthorityService;

    /**
     * 发货通知单管理页面
     */
    @RequiresPermissions("crm:gwai750:init")
    @RequestMapping(value = {"", "init"})
    public String index() {
        return "/pc/crm/gwai750.html";
    }


    /**
     * 查询发货通知单列表
     */
    @RequestMapping("/getListPage")
    @RequiresPermissions("crm:gwai750:init")
    @ResponseBody
    public ResponseData getListPage(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        Dto inDto = dtoWapper.getDto();
        //客户权限
        inDto.put("CUSTOMERS", sysAuthorityService.getCustomersAuthority(inDto));
        List<Map<String, Object>> result = gwecTService.getListPage(page, inDto);
        return new PageReData(page, result);
    }

    /**
     * 抛转
     */
    @RequestMapping("/transform")
    @RequiresPermissions("crm:gwai750:init")
    @ResponseBody
    public ResponseData transform(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        JSONObject jsonObject = inDto.getReqJsonObject();
        List<GwecT> xlist = JSONObject.parseArray(jsonObject.getString("_xdata"), GwecT.class);
        List<GwecT> ylist = JSONObject.parseArray(jsonObject.getString("_ydata"), GwecT.class);
        String mlegal = jsonObject.getString("mlegal");
        //String result = gwecTService.transform(xlist,ylist,mlegal);
        //获取当天最大销货单号
        ShiroUser shiroUser = ShiroKit.getUser();
        String result = "";
        String TG002 = this.gwecTService.getMaxTG002(mlegal, DateUtils.formatDate(new Date(), "yyyyMMdd"));
        for (GwecT yDto : ylist) {
            Dto free_data = Dtos.newDto();
            free_data.put("DOCNO", ylist);
            free_data.put("mlegal", mlegal);
            free_data.put("GWEC003", yDto.getGWEC003());
            free_data.put("GWEC103", yDto.getGWEC103());
            free_data.put("GWEC009", yDto.getGWEC009());
            List<Dto> errList = this.gwecTService.getErr(free_data);
            if (errList.size() > 0) {
                Dto err = errList.get(0);
                String err_message = err.getString("TD004") + "产品+" + err.getString("TD007")
                        + "仓库发货通知单合计" + yDto.getGWEC009() + "大于可用库存量"
                        + err.getString("ERP_NUM");
                return new ErrorResponseData(400, err_message);
            }
        }
        for (GwecT xDto : xlist) {
            String mlegal_x = xDto.getGWECMLEGAL();
            String TC004 = xDto.getGWEC004();
            String TC020 = xDto.getGWEC102();
            Date date = new Date();
            String GWECDOCNO = "CHD" + DateUtils.formatDate(date, DateUtils.PATTERN_yyyyMMddHHmmssSSS);
            int count = 1;
            Dto queryDto = Dtos.newDto();
            for (GwecT yDto : ylist) {
                //根据客户+返利类型+法人进行分单，写入出货通知单表及ERP销货单表
                if (mlegal_x.equals(yDto.getGWECMLEGAL()) && TC004.equals(yDto.getGWEC004()) && TC020.equals(yDto.getGWEC102())) {
                    //根据所选ERP单号+项次获取数据
                    Dto COPTC_D = this.gwecTService.getCOPTCList(yDto.getGWECMLEGAL(), yDto.getGWEC003(), yDto.getGWEC103());
                    COPTC_D.put("TD008",yDto.getGWEC009());
                    COPTC_D.put("TD012", new BigDecimal(yDto.getGWEC009()).multiply(COPTC_D.getBigDecimal("TD011")).multiply(COPTC_D.getBigDecimal("TD026")));
                    BigDecimal shuie = (COPTC_D.getBigDecimal("TD012")).divide(new BigDecimal(1).add(COPTC_D.getBigDecimal("TD037")),2,ROUND_HALF_DOWN);
                    //COPTC_D.put("TD038",COPTC_D.getBigDecimal("TD012").subtract(shuie));
                    COPTC_D.put("TD038",shuie);
                    COPTC_D.put("TD039",(COPTC_D.getBigDecimal("TD012")).subtract(COPTC_D.getBigDecimal("TD038")));
                    queryDto = COPTC_D;
                    //根据品号查询产品资料
                    Dto gwam = this.gwecTService.getGwam(shiroUser.getDBC(), COPTC_D.getString("TD004"));
                    //写入出货通知单
                    GwecT gwecT = new GwecT();
                    gwecT.setGWECENT(shiroUser.getDBC());
                    gwecT.setGWECDOCNO(GWECDOCNO);//单号
                    gwecT.setGWECSEQ(new BigDecimal(count));//单号
                    gwecT.setGWECDOCDATE(LocalDate.now());//单据日期
                    gwecT.setGWEC003(yDto.getGWEC003());//ERP订单号
                    gwecT.setGWEC004(COPTC_D.getString("TD004"));//品号
                    gwecT.setGWEC005(COPTC_D.getString("TC004"));//客户
                    gwecT.setGWEC008(COPTC_D.getString("TC007"));//仓库
                    gwecT.setGWEC009(COPTC_D.getString("TD008"));//数量
                    gwecT.setGWEC016("Y");//有效码

                    try {
                        gwecT.insert();
                    } catch (Exception e) {
                        e.printStackTrace();
                        return new ErrorResponseData(400, "转发货单失败！" + e.getMessage());
                    }
                    try {
                        //写入erp销货单身表
                        this.gwecTService.insertGOPTH(COPTC_D, GWECDOCNO, count, TG002, gwam, mlegal);
                    } catch (Exception e) {
                        this.gwecTService.delGwec(shiroUser.getDBC(), GWECDOCNO);
                        e.printStackTrace();
                        return new ErrorResponseData(400, "转发货单失败！" + e.getMessage());
                    }
                    count++;
                }
            }
            //根据单号查询单身数据汇总
            Dto COPTHSum = this.gwecTService.getCOPTHSum(mlegal, String.valueOf(TG002));
            //写入erp销货单头表
            try {
                this.gwecTService.insertGOPTG(queryDto, GWECDOCNO, count, TG002, COPTHSum, mlegal);
            } catch (Exception e) {
                this.gwecTService.delGwec(shiroUser.getDBC(), GWECDOCNO);
                this.gwecTService.delGOPTH(mlegal, TG002);
                e.printStackTrace();
                return new ErrorResponseData(400, "转发货单失败！" + e.getMessage());
            }
            result = result + TG002 + ",\n";
            BigDecimal num = new BigDecimal(TG002).add(new BigDecimal(1));
            TG002 = num.toString();
        }
        result = StringUtils.substringBeforeLast(result, ",");
        return ResponseData.success(result);
    }

    /**
     * 查询订单列表
     */
    @RequestMapping("/getTcPage")
    @ResponseBody
    public ResponseData getTcPage(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        Dto inDto = dtoWapper.getDto();
        List<Map<String, Object>> result = gwecTService.getCOPTCList(page, inDto);
        return new PageReData(page, result);
    }

}
